<template>
  <div class="dialog">
    <el-dialog :title="'批次' + titleText" :visible.sync="showDialog" width="55%" top="0" :close-on-click-modal="false"
      @close="cancel">
      <el-form ref="ruleForm" label-position="left" :model="formData" :rules="rules" class="el-form">
        <el-form-item label="批次编号:" prop="mnecode" class="w50p">
          <el-input v-model="formData.mnecode" clearable />
        </el-form-item>
        <el-form-item label="码单号:" prop="productionBatchCode" class="w50p">
          <el-input v-model="formData.productionBatchCode" clearable />
        </el-form-item>
        <el-form-item label="供应商:" prop="supplier" class="w50p">
          <el-input v-if="!processNameStr" v-model="formData.supplier" clearable />
          <el-input v-else disabled v-model="processNameStr" clearable />
          <el-button v-if="processNameStr" type="text" @click="() => {
            processNameStr = ''
          }">修改</el-button>
        </el-form-item>
        <el-form-item label="养殖类型:" prop="breedTypeNo" class="w50p">
          <el-select v-model="formData.breedTypeNo" filterable clearable>
            <el-option v-for="(item, index) in breedTypeNoList" :key="index + 'breedTypeNo'" :label="item.breedTypeName"
              :value="item.breedTypeNo" />
          </el-select>
        </el-form-item>
        <el-form-item label="养殖鱼塘:" prop="fishPondId" class="w50p">
          <el-select v-model="formData.fishPondId" filterable clearable @change="pondChange">
            <el-option v-for="(item, index) in fishPondList" :key="index + 'fishPond'"
              v-show="item.pondName.indexOf('监控') == -1"
              :label="`${item.pondName}--${(100 - item.useRatio) == 0 ? '(剩余面积0)' : '(剩余面积' + (100 - item.useRatio) + '%)'}`"
              :value="item.fishPondId" :disabled="(100 - item.useRatio) == 0" />
          </el-select>
        </el-form-item>
        <el-form-item label="鱼塘占比:" prop="pondRatio" class="w50p">
          <el-input v-model="formData.pondRatio" type="number" clearable
            :placeholder="useableRate === undefined ? '请先选择鱼塘' : `剩余可用面积:${useableRate}`">
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="养殖品种:" prop="fishVarietyId" class="w50p">
          <el-select v-model="formData.fishVarietyId" filterable clearable @change="handleChangeFishName">
            <el-option v-for="(item, index) in FishVarietyData" :key="index" :label="item.varietyName"
              :value="item.fishVarietyId" />
          </el-select>
        </el-form-item>
        <!-- prop="clearCompleteFlag" -->
        <el-form-item label="清塘同步完成批次:" prop="clearCompleteFlag" class="w50p">
          <el-select v-model="formData.clearCompleteFlag" filterable clearable>
            <el-option v-for="(item, index) in clearCompleteFlag" :key="index" :label="item.typeName"
              :value="item.typeCode" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间:" prop="buildDateTime" class="w50p">
          <el-date-picker v-model="formData.buildDateTime" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
            placeholder="选择日期时间" :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="选择物料类型:" class="w50p">
           <el-date-picker
      v-model="value1"
      type="datetime"
      placeholder="选择日期时间">
    </el-date-picker>
        </el-form-item>
        <template v-if="varietyName && nowChanceStau == 'add'">
          <el-form-item :label="varietyName ? `活${varietyName}物料:` : '活鱼物料:'" class="w50p">
            <el-select  v-model="formData.liveMaterialId" filterable clearable>
              <el-option v-for="(item, index) in materialList" :key="index" :label="item.name" :value="item.materialId" />
            </el-select>
          </el-form-item>
          <el-form-item :label="varietyName ? `次${varietyName}物料:` : '次鱼物料:'" class="w50p">
            <el-select  v-model="formData.secondaryMaterialId" filterable clearable>
              <el-option v-for="(item, index) in materialList" :key="index" :label="item.name" :value="item.materialId" />
            </el-select>
          </el-form-item>
          <el-form-item :label="varietyName ? `直${varietyName}物料:` : '直鱼物料:'" class="w50p">
            <el-select  v-model="formData.deadMaterialId" filterable clearable>
              <el-option v-for="(item, index) in materialList" :key="index" :label="item.name" :value="item.materialId" />
            </el-select>
          </el-form-item> 
        </template> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button type="primary" class="savebtn" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import FishVarietyApi from "@/api/basic-info-manage/fishVariety"
import FishPondApi from "@/api/basic-info-manage/fishPond"
import BatchMangeApi from "@/api/batch-mange"
import BreedingTypeManageApi from "@/api/basic-info-manage/breeding-type-manage/index";
import ConfigCodeApi from "@/api/basic-info-manage/config-code";
import homeBaseApi from "@/api/basic-info-manage/homeBase";
import MaterialTypeApi from "@/api/basic-info-manage/material";
import MaterialTypeManageApi from "@/api/basic-info-manage/material-type-manage"
import { dialogMixin } from "@/utils/dialogMixin";
let maxTime = null
export default {
  name: '',
  components: {},
  mixins: [dialogMixin],
  props: {
    // 弹框名称
    titleText: {
      type: String,
      default: ""
    },
    nowChanceStau: {
      type: String,
      default: ""
    },
    show: {
      type: Boolean,
      default: false
    },
    editObject: {
      type: [Object],
      default: () => {
        return {}
      }
    }
  },
  data() {
    let checkInt = (rule, value, callback) => {
      if (value) {
        // if (Number(value) && value > 0 && !(value > 100)) {
        //   callback();
        // } else {
        //   return callback(new Error("请输入大于0小于100的参数"));
        // }
        if (Number(value) && value > 0 && !(value > 100) || value == 0 || value == null || value == '' || value == undefined) {
          callback();
        } else {
          return callback(new Error("请输入大于0小于100的参数"));
        }
      }

      // else{
      //   value=''
      //   callback();
      // }
    };
    return {
      deadMaterial: {},
      secondaryMaterial: {},
      liveMaterial: {},
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < new Date(new Date(maxTime).getTime(new Date(maxTime)) - 1000 * 60 * 60 * 24) || time.getTime() > new Date().getTime();
        }
      },
      rules: {
        mnecode: [
          { required: true, message: "请输入批次编号", trigger: ["blur"] }
        ],
        productionBatchCode: [
          { required: true, message: "请输入批次编码", trigger: ["blur"] }
        ],
        breedTypeNo: [
          { required: true, message: "请选择养殖类型", trigger: ["change", "blur"] }
        ],
        fishPondId: [
          { required: true, message: "请选择批次所在鱼塘", trigger: ["blur"] }
        ],
        pondRatio: [
          { required: true, message: "请输入批次鱼塘占比", trigger: ["blur"] },
          { validator: checkInt, trigger: ["change", "blur"] }
        ],
        fishVarietyId: [
          { required: true, message: "请选择养殖品种", trigger: ["blur"] }
        ],
        breedType: [
          { required: true, message: "请选择养殖方式", trigger: ["change", "blur"] }
        ],
        buildDateTime: [
          { required: true, message: "创建时间不能为空", trigger: ["change", "blur"] }
        ],
      },
      formData: {
        productionBatchCode: ''
      },
      //养殖类型
      clearCompleteFlag: [
        {
          typeName: "是",
          typeCode: true,
        },
        {
          typeName: "否",
          typeCode: false,
        },
      ],//是否选项
      useableRate: undefined,
      breedTypeNoList: [],
      fishPondList: [],//鱼塘
      FishVarietyData: [],//品种
      showDialog: this.show,
      materialList: [],
      MaterialTypeManageList: [],
      materialTypeNo: 'FISH',
      varietyName: '',
      processNameStr: '',
    };
  },
  computed: {
  },
  watch: {
    show(v) {
      this.showDialog = v;
      if (!v) {
        this.$refs['ruleForm'].resetFields()
        this.varietyName = null
        console.log('重置表单验证')
      } else {
        this.queryCondition()
        this.queryFishVariety()
        this.queryFishPond()
      }
    },
    nowChanceStau(v) {
      if (v === 'add') {
        this.processNameStr = ''
        this.generateNo();
        homeBaseApi.getBreedTypeNo().then(res => {
          this.formData = {
            staffName: sessionStorage.getItem('staffName'),
            breedTypeNo: res.data,
          }
          this.$set(this.formData, 'buildDateTime', this.formatDateTimeMHS(new Date()))
        })
      }
      if (v === 'edit') {
        this.processNameStr = this.processName(this.editObject.supplier)
        this.formData = this.editObject
        if (!this.formData.productionBatchCode) {
          this.generateNo()
        }
      }
    }
  },
  created() {
  },
  mounted() {
    this.getMaterialTypeManage()
    this.getMaterialType()
  },
  methods: {
    handleChangeFishName(e) {
      console.log(e)
      let fishObj = this.FishVarietyData.filter(function (item) { return item.fishVarietyId == e })
      this.varietyName = fishObj[0].varietyName
    },
    getMaterialTypeManage() {
      MaterialTypeManageApi.queryByCondition().then(res => {
        if (res.data) {
          this.MaterialTypeManageList = res.data
          console.log(this.MaterialTypeManageList, 'MaterialTypeManageList')
        } else {
          this.MaterialTypeManageList = []
        }
      })
    },
    getMaterialType() {
      let params = {
        entity: { materialTypeNo: this.materialTypeNo }
      }
      MaterialTypeApi.queryPageByCondition(params).then(res => {
        if (res.data && res.data.content) {
          this.materialList = res.data.content
          console.log(this.materialList)
        } else {
          this.materialList = []
        }
      })
    },
    generateNo() {
      setTimeout(() => {
        ConfigCodeApi.generateNo({ noType: 'productionBatch' }).then(res => {
          console.log(res.data)
          this.$set(this.formData, 'productionBatchCode', res.data)
        })
      }, 1000)
    },
    queryCondition() {
      BreedingTypeManageApi.queryByCondition().then(res => {
        if (res.success === true) {
          this.breedTypeNoList = res.data || [];
        }
      });
    },
    // 养殖鱼塘
    pondChange(e) {
      this.fishPondList.find(item => {
        if (item.fishPondId === e) {
          this.useableRate = 100 - item.useRatio;
          if (this.useableRate == 0) {
            this.$message.info('改鱼塘无可用面积')
          } else {
            this.$set(this.formData, 'pondRatio', this.useableRate)
          }
          return true
        }
      });
    },
    //查询可选鱼类品种
    queryFishVariety() {
      FishVarietyApi.queryByCondition().then(res => {
        this.FishVarietyData = res.data;
      })
    },
    //查询可选鱼塘
    queryFishPond() {
      FishPondApi.queryByCondition().then(res => {
        this.fishPondList = res.data;
      })
    },
    // 保存
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            if (this.formData.pondRatio < 0) {
              this.$message.error("鱼塘占比介于0~100之间!");
            } else {
              BatchMangeApi.edit(this.formData).then(res => {
                if (res.success === true) {
                  console.log('**', this.formData.pondRatio == '');
                  this.$message.success("修改成功！");
                  this.close()
                } else {
                  this.$message.error(res.message);
                }
              });
            }

          } else if (this.nowChanceStau === "add") {
            if (this.formData.pondRatio < 0) {
              this.$message.error("鱼塘占比介于0~100之间!");
              // this.formData.pondRatio=0
            } else {
              BatchMangeApi.add(this.formData).then(res => {
                if (res.success === true) {
                  this.$message.success("添加成功！");
                  this.close()
                } else {
                  this.$message.error(res.message);
                }
              });
            }
          }
        } else {
          return false;
        }
      });
    },
    close() {
      this.queryFishPond()
      this.useableRate = undefined
      this.$emit("closeDialog");
    },
    cancel() {
      this.$emit("cancelDialog");
    }
  }
};
</script>

<style lang="scss" scoped></style>
